package com.zzmcc.wechat.util;

import java.io.InputStream;
import java.util.*;

import org.apache.commons.codec.digest.DigestUtils;
import org.smart4j.framework.util.CastUtil;
import org.smart4j.framework.util.PropsUtil;

public final class Tools {
    /**
     * SQL 属性文件对象
     */
    private static final Properties inMsgProps = PropsUtil.loadProps("inMessage.properties");

    /**
     * 从 SQL 属性文件中获取相应的 SQL 语句
     */
    public static String getMsg(String key) {
        String inMsg;
        if (inMsgProps.containsKey(key)) {
            inMsg = inMsgProps.getProperty(key);
        } else {
            throw new RuntimeException("无法在文件中获取属性：" + key);
        }
        return inMsg;
    }

	public static final String inputStream2String(InputStream in) {
		if(in == null)
			return "";
		try{
            StringBuffer out = new StringBuffer();
            byte[] b = new byte[4096];
            for (int n; (n = in.read(b)) != -1;) {
                out.append(new String(b, 0, n, "UTF-8"));
            }
            return CastUtil.castString(out);
        }catch (Exception e){
            return  "";
        }

	}

	
	public static final boolean checkSignature(String token,String signature,String timestamp,String nonce){
		List<String> params = new ArrayList<String>();
		params.add(token);
		params.add(timestamp);
		params.add(nonce);
		Collections.sort(params,new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				return o1.compareTo(o2);
			}
		});
		String temp = params.get(0)+params.get(1)+params.get(2);
		return DigestUtils.shaHex(temp).equals(signature);
	}
}
